import { NextRequest, NextResponse } from 'next/server';
import { getUserManagement } from '@/lib/user-management';
import { cookies } from 'next/headers';

// GET /api/admin/roles - 获取所有角色
export async function GET(request: NextRequest) {
  try {
    const cookieStore = await cookies();
    const sessionToken = cookieStore.get('session_token')?.value;

    if (!sessionToken) {
      return NextResponse.json({
        success: false,
        error: '未登录'
      }, { status: 401 });
    }

    const userMgmt = getUserManagement();
    const user = userMgmt.validateSession(sessionToken);

    if (!user) {
      return NextResponse.json({
        success: false,
        error: '会话已过期'
      }, { status: 401 });
    }

    const roles = userMgmt.getAllRoles();

    // 解析权限信息
    const rolesWithParsedPermissions = roles.map(role => ({
      ...role,
      parsedPermissions: userMgmt.parseRolePermissions(role.permissions)
    }));

    return NextResponse.json({
      success: true,
      data: rolesWithParsedPermissions
    });

  } catch (error) {
    console.error('获取角色列表失败:', error);
    return NextResponse.json({
      success: false,
      error: '获取角色列表失败'
    }, { status: 500 });
  }
}
